package com.xd.shading.config.sharding;

import com.alibaba.druid.support.json.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.*;

/**
 * 分表算法
 */
@Slf4j
public class TableStandardShardingAlgorithm implements StandardShardingAlgorithm<Long> {



    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        log.info("进入TableStandardShardingAlgorithm的doSharding1方法：" + JSONUtils.toJSONString(collection));

        String actuallyTable = preciseShardingValue.getLogicTableName() + "_" + (preciseShardingValue.getValue() % 3);

        Collection<String> tables = AutoCreateTableHelper.getInstance()
                .autoDetectionSchemeTables(preciseShardingValue.getLogicTableName(),
                        Collections.singletonList(actuallyTable), true);
        collection.addAll(tables);
        return CollectionUtils.get(tables, 0);
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        log.info("进入TableStandardShardingAlgorithm的doSharding2方法：" + rangeShardingValue);
        log.info("进入TableStandardShardingAlgorithm的doSharding2方法：" + JSONUtils.toJSONString(collection));
        return collection;
    }

    @Override
    public void init() {
        log.info("进入TableStandardShardingAlgorithm的init方法");
    }

    @Override
    public String getType() {
        log.info("进入TableStandardShardingAlgorithm的getType方法");
        return "STANDARD";
    }
}
